<script setup>
import { ref, onMounted, watch } from 'vue'
import { useRoute } from 'vue-router'
import { ethers } from 'ethers'
import * as echarts from 'echarts'
import DonationPlatformJson from 'E:/Vue3/vite-project/artifacts/contracts/DonationPlatform.sol/DonationPlatform.json'

const route = useRoute()
const projectId = route.query.projectId
const txHash = route.query.txHash

const contractAddress = '0x1f936366c9b21fC9343BC2DC710031aa01be072E'
const abi = DonationPlatformJson.abi

const project = ref(null)
const donationRecord = ref(null)
const fundFlow = ref([])

let provider, signer, contract

async function init() {
  if (!projectId) {
    alert('缺少项目ID')
    return
  }
  if (!window.ethereum) {
    alert('请安装MetaMask或其他Web3钱包')
    return
  }

  provider = new ethers.providers.Web3Provider(window.ethereum)
  await provider.send('eth_requestAccounts', [])
  signer = provider.getSigner()
  contract = new ethers.Contract(contractAddress, abi, signer)

  try {
    const p = await contract.getProject(projectId)
    project.value = {
      id: p.id.toString(),
      name: p.name,
      description: p.description,
      goal: parseFloat(ethers.utils.formatEther(p.goal)),
      raised: parseFloat(ethers.utils.formatEther(p.raised)),
      image: p.image || 'https://via.placeholder.com/400x300?text=项目图片'
    }
  } catch (e) {
    console.error('加载项目失败', e)
  }

  if (txHash) {
    try {
      const tx = await provider.getTransaction(txHash)
      const receipt = await provider.getTransactionReceipt(txHash)
      donationRecord.value = {
        txHash,
        from: tx.from,
        to: tx.to,
        value: ethers.utils.formatEther(tx.value),
        gasUsed: receipt.gasUsed.toString(),
        blockNumber: receipt.blockNumber
      }
    } catch (e) {
      console.error('加载交易详情失败', e)
    }
  }

  try {
    const flows = await contract.getFundFlows(projectId)
    fundFlow.value = flows.map(f => ({
      title: f.title,
      description: f.description,
      amount: parseFloat(ethers.utils.formatEther(f.amount)),
      date: new Date(f.timestamp.toNumber() * 1000).toLocaleDateString(),
      status: f.status,
      statusText: f.statusText,
      txHash: f.txHash
    }))
  } catch (e) {
    console.warn('加载资金流向失败，显示模拟数据')
    fundFlow.value = [
      {
        title: '项目启动资金',
        description: '初期筹资到位并转入项目地址',
        amount: 10,
        date: new Date().toLocaleDateString(),
        status: 'completed',
        statusText: '已完成',
        txHash: ''
      }
    ]
  }

  renderCharts()
}

function renderCharts() {
  const pieDom = document.getElementById('pieChart')
  const barDom = document.getElementById('barChart')
  if (!pieDom || !barDom || fundFlow.value.length === 0) return

  const pieChart = echarts.init(pieDom)
  const barChart = echarts.init(barDom)

  // 饼图数据：标题和金额
  const pieData = fundFlow.value.map(f => ({
    name: f.title,
    value: f.amount
  }))

  // 柱状图数据：日期与金额，按日期升序
  // 把相同日期金额合并
  const dateMap = {}
  fundFlow.value.forEach(f => {
    if (!dateMap[f.date]) dateMap[f.date] = 0
    dateMap[f.date] += f.amount
  })
  const barCategories = Object.keys(dateMap).sort((a,b) => new Date(a) - new Date(b))
  const barValues = barCategories.map(d => dateMap[d])

  pieChart.setOption({
    title: { text: '资金流向占比', left: 'center' },
    tooltip: { trigger: 'item' },
    legend: { bottom: 0 },
    series: [
      {
        name: '金额',
        type: 'pie',
        radius: '50%',
        data: pieData,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  })

  barChart.setOption({
    title: { text: '资金流向时间趋势', left: 'center' },
    tooltip: { trigger: 'axis' },
    xAxis: {
      type: 'category',
      data: barCategories,
      axisLabel: { rotate: 45 }
    },
    yAxis: { type: 'value' },
    series: [
      {
        data: barValues,
        type: 'bar',
        itemStyle: { color: '#4f46e5' }
      }
    ]
  })
}

// fundFlow变化时自动刷新图表
watch(fundFlow, () => {
  renderCharts()
})

onMounted(() => {
  init()
})
</script>

<template>
  <div class="container mx-auto p-6">
    <h1 class="text-3xl mb-6 font-bold">项目资金流向追踪</h1>

    <div v-if="project">
      <h2 class="text-xl font-semibold">{{ project.name }}</h2>
      <p>{{ project.description }}</p>
      <p>目标资金：{{ project.goal }} ETH</p>
      <p>已筹资金：{{ project.raised }} ETH</p>
      <img :src="project.image" alt="项目图片" class="w-96 h-64 object-cover rounded" />
    </div>

    <div v-if="donationRecord" class="mt-6 p-4 border rounded">
      <h3 class="text-lg font-semibold">本次捐赠详情</h3>
      <p>交易哈希：<a :href="`https://etherscan.io/tx/${donationRecord.txHash}`" target="_blank" class="text-blue-600 underline">{{ donationRecord.txHash }}</a></p>
      <p>捐赠地址：{{ donationRecord.from }}</p>
      <p>接收地址：{{ donationRecord.to }}</p>
      <p>捐赠金额：{{ donationRecord.value }} ETH</p>
      <p>区块号：{{ donationRecord.blockNumber }}</p>
      <p>Gas 用量：{{ donationRecord.gasUsed }}</p>
    </div>

    <!-- 图表展示 -->
    <div class="mt-6 grid grid-cols-1 md:grid-cols-2 gap-6">
      <div id="pieChart" style="height: 350px;"></div>
      <div id="barChart" style="height: 350px;"></div>
    </div>

    <div class="mt-6">
      <h3 class="text-lg font-semibold mb-3">资金流向详情</h3>
      <ul>
        <li v-for="(flow, index) in fundFlow" :key="index" class="mb-4 p-3 border rounded">
          <p><strong>{{ flow.title }}</strong> ({{ flow.statusText }})</p>
          <p>{{ flow.description }}</p>
          <p>金额: {{ flow.amount }} ETH</p>
          <p>日期: {{ flow.date }}</p>
          <p v-if="flow.txHash">交易哈希: 
            <a :href="`https://etherscan.io/tx/${flow.txHash}`" target="_blank" class="text-blue-600 underline">
              {{ flow.txHash.slice(0, 10) + '...' }}
            </a>
          </p>
        </li>
      </ul>
    </div>
  </div>
</template>

<style scoped>
.container {
  max-width: 960px;
  margin: 0 auto;
  padding: 1.5rem;
  font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
  color: #222;
  background-color: #fafafa;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgb(0 0 0 / 0.1);
}

/* 标题 */
h1 {
  color: #3b82f6; /* 蓝色 */
  text-align: center;
  margin-bottom: 1rem;
  font-weight: 700;
}

h2 {
  margin-top: 1rem;
  margin-bottom: 0.5rem;
  color: #1e293b; /* 深蓝灰 */
  font-weight: 600;
}

h3 {
  color: #334155; /* 中深灰 */
  font-weight: 600;
  margin-bottom: 0.75rem;
}

/* 项目描述段落 */
p {
  line-height: 1.6;
  margin-bottom: 0.75rem;
  color: #475569;
}

/* 项目图片 */
img {
  display: block;
  border-radius: 8px;
  box-shadow: 0 4px 10px rgb(0 0 0 / 0.05);
  max-width: 100%;
  height: auto;
  margin-top: 0.5rem;
}

/* 交易详情盒子 */
.mt-6 {
  margin-top: 1.5rem;
}

.border {
  border: 1px solid #cbd5e1;
  background-color: #fff;
}

.p-4 {
  padding: 1rem;
}

.rounded {
  border-radius: 8px;
}

.text-blue-600 {
  color: #2563eb;
}

.text-blue-600:hover {
  text-decoration: underline;
}

/* 图表容器 */
#pieChart, #barChart {
  background-color: #ffffff;
  border-radius: 8px;
  box-shadow: 0 4px 8px rgb(0 0 0 / 0.1);
}

/* 资金流向列表 */
ul {
  list-style: none;
  padding-left: 0;
}

li {
  background-color: #ffffff;
  border: 1px solid #e2e8f0;
  padding: 1rem;
  border-radius: 8px;
  transition: box-shadow 0.3s ease;
}

li:hover {
  box-shadow: 0 4px 12px rgb(59 130 246 / 0.25);
}

/* 响应式网格布局 */
.grid {
  display: grid;
  gap: 1.5rem;
}

@media (min-width: 768px) {
  .grid-cols-2 {
    grid-template-columns: repeat(2, 1fr);
  }
}

/* 链接样式 */
a {
  color: #2563eb;
  cursor: pointer;
}

a:hover {
  text-decoration: underline;
}

/* 资金流向条目标题 */
li p strong {
  font-weight: 700;
  color: #1e293b;
}

/* 滚动条样式（可选） */
.container::-webkit-scrollbar {
  width: 8px;
}

.container::-webkit-scrollbar-thumb {
  background-color: #a5b4fc;
  border-radius: 4px;
}
</style>

